package com.upc.toss.slice;

import com.upc.toss.MainAbility;
import com.upc.toss.ResourceTable;
import com.upc.toss.fraction.MainFraction;
import com.upc.toss.util.DataBaseController;
import com.upc.toss.util.Get;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.logging.Handler;
import java.util.logging.LogRecord;


public class LoginAbilitySlice extends AbilitySlice {

    TextField et_username;
    TextField et_password;
    Button loginBtn;


    private String token;
    MyEventHandler handler;
    DataBaseController baseController;
    Preferences preferences;
    public static Context context;

    String password;
    String username;
    @Override
    public void onStart(Intent intent) {
        context=this;
        super.onStart(intent);
        EventRunner runner = EventRunner.current();
        handler = new MyEventHandler(runner);
        DatabaseHelper databaseHelper = new DatabaseHelper(this); // context入参类型为ohos.app.Context。
        preferences = databaseHelper.getPreferences("user");// user表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。

        if(!"".equals(preferences.getString("username", ""))){
            // 点击按钮跳转至第二个页面
            Intent intent1= new Intent();
            // 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.upc.toss")
                    .withAbilityName("com.upc.toss.MainAbility")
                    .build();
            intent1.setOperation(operation);
            startAbility(intent1);
            terminate();
        }
        super.setUIContent(ResourceTable.Layout_ability_login);
        baseController=new DataBaseController();
        init();
    }

    public void init() {
        loginBtn = (Button) findComponentById(ResourceTable.Id_btn_login);
        et_username = (TextField) findComponentById(ResourceTable.Id_textField_username);
        et_password = (TextField) findComponentById(ResourceTable.Id_textField_password);
        loginBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                username = et_username.getText().toString().trim();
                password = et_password.getText().toString().trim();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                       int code= baseController.isLogin(username,password);
                        if(code==100){
                            preferences.putString("username",username);
                            preferences.flush();
                            handler.sendEvent(1);
                        }else{
                            handler.sendEvent(2);
                        }
                    }
                }).start();
            }
        });
    }

    private class MyEventHandler extends EventHandler {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }
        // 重写实现processEvent方法
        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case 1:
                    Intent intent= new Intent();
                    // 通过Intent中的OperationBuilder类构造operation对象，
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")//指定设备标识（空串表示当前设备）
                            .withBundleName("com.upc.toss")//应用包名
                            .withAbilityName("com.upc.toss.MainAbility")//Ability名称
                            .build();

                    intent.setParam("name",username);
                    intent.setOperation(operation);// 把operation设置到intent中
                    startAbility(intent);
                    terminate();        //结束当前页面
                    Intent intent1 = new Intent();
                    intent1.setParam("name2",username);
                    break;
                case 2:
                    new ToastDialog(context).setText("Wrong!").show();
                    break;
                default:
                    break;
            }
        }
    }



    @Override
    public void onActive () {
        super.onActive();
    }
    public void onInactive () {
        super.onInactive();
    }
    public void onBackground () {
        super.onBackground();
    }

    public void onStop () {
        super.onStop();
    }
}
